package com.music.note_android.ui.notelist

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.music.note_android.R
import com.music.note_android.data.model.Note
import com.music.note_android.databinding.ItemNoteBinding
import com.music.note_android.utils.ThumbnailLoader
import java.io.File

class NoteListAdapter(
    private val lifecycleOwner: LifecycleOwner,
    private val onNoteClick: (Note) -> Unit,
    private val onNoteLongClick: (Note) -> Unit,
    private val onSelectionChanged: (String, Boolean) -> Unit
) : ListAdapter<Note, NoteListAdapter.NoteViewHolder>(NoteDiffCallback()) {
    
    private var isSelectionMode = false
    private var selectedNoteIds = setOf<String>()
    private lateinit var thumbnailLoader: ThumbnailLoader
    
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoteViewHolder {
        val binding = ItemNoteBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        
        // 初始化缩略图加载器
        if (!::thumbnailLoader.isInitialized) {
            thumbnailLoader = ThumbnailLoader.getInstance(parent.context)
        }
        
        return NoteViewHolder(binding)
    }
    
    override fun onBindViewHolder(holder: NoteViewHolder, position: Int) {
        holder.bind(getItem(position))
    }
    
    fun setSelectionMode(selectionMode: Boolean) {
        if (isSelectionMode != selectionMode) {
            isSelectionMode = selectionMode
            notifyDataSetChanged()
        }
    }
    
    fun updateSelection(selectedIds: Set<String>) {
        val oldSelection = selectedNoteIds
        selectedNoteIds = selectedIds
        
        // 只更新选择状态发生变化的项目
        currentList.forEachIndexed { index, note ->
            val wasSelected = oldSelection.contains(note.id)
            val isSelected = selectedIds.contains(note.id)
            if (wasSelected != isSelected) {
                notifyItemChanged(index)
            }
        }
    }
    
    inner class NoteViewHolder(private val binding: ItemNoteBinding) :
        RecyclerView.ViewHolder(binding.root) {
        
        fun bind(note: Note) {
            binding.apply {
                // 设置笔记标题
                tvTitle.text = note.getDisplayTitle()
                
                // 设置修改时间
                tvTime.text = note.getFormattedModifiedTime()
                
                // 加载缩略图
                loadThumbnail(note)
                
                // 设置选择状态
                val isSelected = selectedNoteIds.contains(note.id)
                updateSelectionUI(isSelected)
                
                // 设置点击事件
                root.setOnClickListener {
                    onNoteClick(note)
                }
                
                root.setOnLongClickListener {
                    onNoteLongClick(note)
                    true
                }
                
                // 复选框点击事件
                cbSelected.setOnCheckedChangeListener { _, isChecked ->
                    if (isSelectionMode && isChecked != isSelected) {
                        onSelectionChanged(note.id, isChecked)
                    }
                }
            }
        }
        
        private fun loadThumbnail(note: Note) {
            binding.apply {
                // 使用ThumbnailLoader加载缩略图
                thumbnailLoader.loadThumbnail(
                    noteId = note.id,
                    thumbnailPath = note.thumbnailPath,
                    dataPath = note.dataPath,
                    imageView = ivThumbnail,
                    placeholderResId = R.drawable.ic_note_placeholder,
                    scope = lifecycleOwner.lifecycleScope
                )
                
                // 根据是否有缩略图显示不同的UI
                if (note.hasThumbnail()) {
                    ivThumbnail.isVisible = true
                    ivPlaceholder.isVisible = false
                } else {
                    // 显示占位符，但仍然尝试生成缩略图
                    showPlaceholder()
                }
            }
        }
        
        private fun showPlaceholder() {
            binding.apply {
                ivThumbnail.isVisible = false
                ivPlaceholder.isVisible = true
                ivPlaceholder.setImageResource(R.drawable.ic_note_placeholder)
            }
        }
        
        private fun updateSelectionUI(isSelected: Boolean) {
            binding.apply {
                // 显示/隐藏选择相关UI
                selectionOverlay.isVisible = isSelectionMode
                cbSelected.isVisible = isSelectionMode
                
                if (isSelectionMode) {
                    // 设置选择状态
                    cbSelected.isChecked = isSelected
                    
                    // 设置选择覆盖层的透明度
                    selectionOverlay.alpha = if (isSelected) 0.3f else 0.0f
                    
                    // 设置卡片的选择状态样式
                    cardNote.isChecked = isSelected
                } else {
                    // 非选择模式，隐藏选择UI
                    cardNote.isChecked = false
                }
            }
        }
    }
    
    class NoteDiffCallback : DiffUtil.ItemCallback<Note>() {
        override fun areItemsTheSame(oldItem: Note, newItem: Note): Boolean {
            return oldItem.id == newItem.id
        }
        
        override fun areContentsTheSame(oldItem: Note, newItem: Note): Boolean {
            return oldItem == newItem
        }
    }
}